package com.liuyi.tools.kits;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.liuyi.tools.web.resp.Response;
import com.liuyi.tools.web.unusual.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName RequestTool.java
 * @Description TODO request工具集
 * @createTime 2019年06月24日 14:02:00
 */
@Slf4j
public class RequestKit {

    public static String getOrder() {
        String order = getRequest().getParameter("order");
        return StrUtil.isBlank(order) ? null : StrUtil.toUnderlineCase(order);
    }

    public static boolean getOrderBy() {
        String orderBy = getRequest().getParameter("orderBy");
        return StrUtil.isBlank(orderBy) ? false : Boolean.valueOf(orderBy);
    }

    public static Integer getPageIndex() {
        String pageIndex = getRequest().getParameter("page");
        return StrUtil.isBlank(pageIndex) ? 1 : NumberUtil.parseInt(pageIndex);
    }

    public static Integer getPageSize() {
        String pageSize = getRequest().getParameter("limit");
        return StrUtil.isBlank(pageSize) ? 10 : NumberUtil.parseInt(pageSize);
    }

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNotNull(requestAttributes) && requestAttributes instanceof ServletRequestAttributes) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            return servletRequestAttributes.getRequest();
        }
        return null;
    }

    /**
     * 返回参数
     */
    public static void responseWriter(HttpServletResponse response, HttpStatus httpStatus, Response responseWriter) throws IOException {
        response.setStatus(httpStatus.value());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.println(JSONObject.toJSONString(responseWriter));
        }
    }

    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip.split(",")[0];
    }

    /**
     * 是否是Json请求
     */
    public static boolean isJsonRequest(HttpServletRequest request) {
        String header = request.getHeader(HttpHeaders.CONTENT_TYPE);
        return MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(header)
                || MediaType.APPLICATION_JSON_UTF8_VALUE.equalsIgnoreCase(header);
    }

    public static Dict getJson(HttpServletRequest request) {
        if (isJsonRequest(request)) {
            try (ServletInputStream inputStream = request.getInputStream()) {
                String json = IoUtil.read(inputStream, "utf8");
                if (StrUtil.isNotBlank(json)) {
                    return JSONUtil.toBean(json,Dict.class);
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public static String getRealIpV2(HttpServletRequest request) {
        String accessIp = request.getHeader("x-forwarded-for");
        return null == accessIp ? request.getRemoteAddr() : accessIp;
    }
}
